import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import MainView from "../views/MainView.vue";
import Library from "../components/Library.vue";
import LoginView from "../components/LoginView.vue";
import Register from "@/components/Register.vue";
import Record from "@/components/Record.vue";
import UserManager from "@/components/UserManager.vue";
import UserInformation from "@/components/UserInformation.vue";
import UserPasswd from "@/components/UserPasswd.vue";
import FaceScan from "@/components/FaceScan.vue";
// import { checkToken } from "@/api/auth"; // 用于验证 token 的 API 请求

import Show from "@/views/show.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      component: MainView, // 布局组件，包含 <RouterView>
      meta: { requiresAuth: true },
      children: [
        {
          path: "/",
          name: "home",
          component: HomeView,
        },
        {
          path: "library", // 图书列表子路由
          name: "library",
          component: Library,
        },
        {
          path: "/record",
          name: "record",
          component: Record,
        },
        {
          path: "/manager",
          name: "manager",
          component: UserManager,
        },
        {
          path: "/information",
          name: "information",
          component: UserInformation,
        },
        {
          path: "/passwd",
          name: "passwd",
          component: UserPasswd,
        }
    
      ],
    },
    // {
    //   path: "/",
    //   name: "Home",
    //   component: HomeView,
    //   meta: { requiresAuth: true },
    // },
    {
      path: "/login",
      name: "login",
      component: LoginView,
    },
    {
      path: "/register",
      name: "register",
      component: Register,
    },
    {
      path: "/show",
      name: "show",
      component: Show,
    },
    {
      path: "/facescan",
      name: "facescan",
      component: FaceScan,
    },
  ],
});

// 全局导航守卫：在每次进入页面前验证 token
// 在 beforeEach 中添加跳转逻辑
router.beforeEach(async (to, from, next) => {
  const token = document.cookie
    .split("; ")
    .find((row) => row.startsWith("token="))
    ?.split("=")[1];

  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (token) {
      try {
        {
          next();
        }
      } catch (error) {
        console.error("Token verification failed:", error);
        next("/login");
      }
    } else {
      next("/login");
    }
  } else {
    next();
  }
});

export default router;
